package com.lizhe.jpa.service;

import com.lizhe.jpa.dao.ArticleRepository;
import com.lizhe.jpa.model.Article;
import com.lizhe.jpa.model.ArticleVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * 类描述:
 *
 * @author Administrator
 * @create 2021-10-27 21:41
 */
@Service
public class ArticleJPAService {

    @Resource
    private ArticleRepository articleRepository;

    public void saveArticle(ArticleVO articleVO) {
        Article article = new Article();
        // 对象的转换
        BeanUtils.copyProperties(articleVO, article);
        articleRepository.save(article);
    }

    public void deleteArticleById(Integer id) {
        articleRepository.deleteById(id);
    }

    public List<Article> getAll() {
        return articleRepository.findAll();
    }

    public Article findById(Integer id) {
        Optional<Article> article = articleRepository.findById(id);
        return article.get();
    }

    // 这是根据名字自动生成的 SQL 方法
    public Article findByAuthor(String author) {
        return articleRepository.findByAuthor(author);
    }
}
